<template>
    <!-- <el-scrollbar height="740px"> -->
    <div class="common-layout">
        <el-container>
            <el-header>
                <div class="logo1">
                    <!-- <img src="../img/设计 WMS 系统 logo.png" alt="" width="75" height="75"> -->
                    富联WMS
                </div>
                <div class="sys">
                    <div class="close" @click="close">
                        <!-- <el-icon style="text-align: center;">
                            <CloseBold />
                        </el-icon>退出登录 -->
                        <!-- icon-tuichu -->
                        <svg-icon iconName="icon-tuichu"></svg-icon>退出登录
                    </div>
                    <div class="userName">
                        欢迎您，{{ name }}
                    </div>
                </div>
            </el-header>
            <el-container style="height: 668px;">
                <el-aside width="170px" style="background-color: #fafafa;">
                    <el-menu default-active="1" class="el-menu-vertical-demo" :collapse="isCollapse"
                        :collapse-transition="false" :router="true" :unique-opened="true">
                        <!-- <div class="toggle-button" @click="gb()">|||</div> -->
                        <!--一级菜单-->
                        <el-sub-menu :index="item.jurId + ''" v-for="item in list" :key="item.jurId"
                            @click="handleFirstLevelMenuClick(item)">
                            <template #title>
                                <el-icon>
                                    <HomeFilled />
                                </el-icon>
                                <span>{{ item.jurName }}</span>
                            </template>
                            <!--二级菜单-->
                            <el-menu-item :index="item1.jurAddress + ''" v-for="item1 in item.children"
                                :key="item1.jurId" @click="handleMenuClick(item1)">
                                <el-icon>
                                    <CopyDocument />
                                </el-icon>
                                <span>{{ item1.jurName }}</span>
                            </el-menu-item>
                        </el-sub-menu>
                    </el-menu>
                </el-aside>
                <el-main>
                    <div class="tabs-header">
                        <el-tabs v-model="editableTabsValue" type="card" closable class="demo-tabs"
                            @edit="handleTabsEdit" @tab-click="handleTabClick">
                            <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title"
                                :name="item.name">
                                <!-- 这里留空，不显示任何内容 -->
                            </el-tab-pane>
                        </el-tabs>
                        <el-button @click="clearAllTabs" size="small"
                            style="margin-left:10px; height:40px;margin-top: -60px;border-bottom: 0px;">
                            关闭所有
                        </el-button>
                    </div>
                    <RouterView></RouterView>
                </el-main>
            </el-container>
        </el-container>
    </div>
    <!-- </el-scrollbar> -->
</template>
<script>
import { ref, reactive, watch, provide } from 'vue'
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';
import { TabPaneName } from 'element-plus'
import { useStore } from 'vuex';

export default {
    setup() {
        const store = useStore();
        const router = useRouter();
        const route = useRoute();
        const name = ref("")
        const list = ref([])
        name.value = localStorage.getItem('userLName')

        const isCollapse = ref(false);

        // 根据路径查找对应的菜单项
        const findMenuItemByPath = (path) => {
            for (const item of list.value) {
                if (item.children) {
                    const found = item.children.find(child => child.jurAddress === path);
                    if (found) return found;
                }
            }
            return null;
        };

        // 查询角色对应的权限信息
        function fill() {
            axios.get("http://localhost:5181/api/Jurisdiction/GetJurisdictions", {
                params: {
                    rolesId: localStorage.getItem('rolesId')
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                list.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        fill()

        // 退出登录
        function close() {
            router.push('/login')
            localStorage.removeItem("token")
            localStorage.removeItem("rolesId")
            localStorage.removeItem("userId")
            localStorage.removeItem("userLName")
        }

        const tabIndex = ref(2);
        const editableTabsValue = ref(route.path);
        const editableTabs = ref([
            {
                title: '首页',
                name: '/main',
                path: '/main'
            }
        ])

        // 根据路由信息添加或激活标签页
        const addOrActivateTab = (path, title) => {
            const existingTab = editableTabs.value.find(tab => tab.path === path);

            if (!existingTab && path !== "/") {
                // 尝试从路由的 meta 获取标题
                const route = router.resolve(path); // 解析路由
                const tabTitle = route.meta?.title || title || "新标签";

                editableTabs.value.push({
                    title: tabTitle,
                    name: path,
                    path: path,
                });
            }

            editableTabsValue.value = path;
        };

        // 监听路由变化
        watch(() => route.path, (newPath) => {
            if (newPath) {
                const menuItem = findMenuItemByPath(newPath);
                const title = menuItem ? menuItem.jurName : '新标签';
                addOrActivateTab(newPath, title);
            }
        }, { immediate: true });

        const handleTabsEdit = (targetName, action) => {
            if (action === 'add') {
                const newTabName = `${++tabIndex.value}`;
                editableTabs.value.push({
                    title: '新选项卡',
                    name: newTabName,
                    path: '/new-tab'
                });
                editableTabsValue.value = newTabName;
                router.push('/new-tab');
            } else if (action === 'remove' && targetName) {
                const tabs = editableTabs.value;
                let activeName = editableTabsValue.value;

                if (activeName === targetName) {
                    tabs.forEach((tab, index) => {
                        if (tab.name === targetName) {
                            const nextTab = tabs[index + 1] || tabs[index - 1];
                            if (nextTab) {
                                activeName = nextTab.name;
                                router.push(nextTab.path);
                            } else {
                                router.push('/main');
                            }
                        }
                    });
                }

                editableTabs.value = tabs.filter(tab => tab.name !== targetName);
                editableTabsValue.value = activeName;
            }
        };

        const handleTabClick = (tab) => {
            const targetTab = editableTabs.value.find(item => item.name === tab.paneName);
            if (targetTab && targetTab.path) {
                router.push(targetTab.path);
            }
        };

        const handleMenuClick = (menuItem) => {
            if (menuItem.jurAddress) {
                router.push(menuItem.jurAddress);
            }
        };

        const closeCurrentTab = () => {
            const currentPath = route.path;
            editableTabs.value = editableTabs.value.filter(tab => tab.path !== currentPath);

            if (editableTabsValue.value === currentPath) {
                editableTabsValue.value = editableTabs.value[editableTabs.value.length - 1]?.path || '/main';
            }
        };

        provide('closeTab', closeCurrentTab); // 提供关闭方法

        function handleFirstLevelMenuClick(item) {
            console.info(item)
            if (item.jurName === "系统首页") {
                router.push('/main')
            }
        }

        //关闭所有标签栏，回到首页
        const clearAllTabs = () => {
            // 保留首页标签（name为'/main'的标签）
            const homeTab = editableTabs.value.find(tab => tab.name === '/main');
            editableTabs.value = homeTab ? [homeTab] : [];
            editableTabsValue.value = homeTab ? homeTab.name : '';

            // 如果当前不在首页则跳转
            if (route.path !== '/main') {
                router.replace('/main');
            }
        };

        return {
            name,
            isCollapse,
            list,
            close,
            tabIndex,
            editableTabsValue,
            editableTabs,
            handleTabsEdit,
            handleTabClick,
            handleMenuClick, closeCurrentTab, handleFirstLevelMenuClick, clearAllTabs
        }
    }
}
</script>
<style>
/* 针对菜单项禁用焦点和选择样式 */
.el-menu-item, .el-sub-menu__title {
  user-select: none; /* 禁止文本选择 */
  outline: none; /* 去除焦点轮廓 */
}

/* 进一步阻止焦点行为 */
.el-menu-item:focus, .el-sub-menu__title:focus {
  outline: none !important;
  box-shadow: none !important;
}

/* 全局去除 Element UI 菜单及交互元素的焦点光标和选择样式 */
.el-menu,
.el-menu-item,
.el-sub-menu,
.el-sub-menu__title,
.el-menu--vertical .el-menu-item,
.el-menu--vertical .el-sub-menu__title {
  /* 禁止文本被选择（避免选择文本时出现光标） */
  user-select: none;
  -webkit-user-select: none;
}

/* 去除所有焦点状态的轮廓（避免点击后出现焦点边框/光标） */
.el-menu-item:focus,
.el-sub-menu__title:focus,
.el-menu-item:focus-within,
.el-sub-menu__title:focus-within {
  outline: none !important;
  box-shadow: none !important;
}

/* 进一步阻止表单类元素的默认焦点行为（如果有嵌套输入框） */
.el-menu *:focus {
  outline: none;
}

/* 全局去除日期选择器的输入光标及焦点样式 */
.el-date-editor,
.el-date-editor .el-input,
.el-date-editor .el-input__inner {
  /* 禁止文本选择，避免光标出现 */
  user-select: none;
  -webkit-user-select: none;
}

/* 去除输入框焦点状态的轮廓和光标 */
.el-date-editor .el-input__inner:focus {
  outline: none !important;
  box-shadow: none !important;
  /* 部分浏览器可能需要额外隐藏光标 */
  caret-color: transparent !important;
}

/* 针对范围选择器的特殊处理 */
.el-date-range-picker .el-input__inner:focus {
  outline: none !important;
  caret-color: transparent !important;
}
.logo1 {
    /* background-color: #239bff; */
    font-weight: bold;
    text-align: center;
    line-height: 60px;
    width: 12%;
    height: 100%;
}

.tabs-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.demo-tabs {
    flex: 1;
    /* 让标签栏占据剩余空间 */
}

.scrollbar-demo-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    margin: 10px;
    text-align: center;
    border-radius: 4px;
    background: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
}

.sys {
    margin-top: -60px;
    float: right;
    text-align: center;
    line-height: 60px;
    width: 23%;
    height: 100%;
}

.close {
    margin-top: 14px;
    float: right;
    text-align: center;
    line-height: 38px;
    width: 107px;
    height: 53%;
}

.userName {
    margin-top: 14px;
    float: right;
    text-align: center;
    line-height: 38px;
    width: 160px;
    height: 53%;
    margin-right: 9px;
}

.close:hover {
    color: #239bff;
    background-color: #e9f3ff;
}

.userName:hover {
    color: #239bff;
    background-color: #e9f3ff;
}

.toggle-button {
    background-color: #4A5064;
    font-size: 10px;
    text-align: center;
    color: #fff;
    line-height: 24px;
    letter-spacing: 0.2em;
    cursor: pointer;
}

.el-menu-vertical-demo {
    background-color: #fafafa;
}

.el-main {
    width: 100%;
    background-color: #ffffff;
    margin: 15px;
}

.el-header {
    width: 100%;
    background-color: #ffffff;
}

.el-container {
    background-color: #fafafa;
}

.demo-tabs>.el-tabs__content {
    padding: 3px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;

}

.demo-tabs {
    position: relative;
    top: -19px;
    overflow-x: auto
}
.no-cursor {
  cursor: none;
}
</style>